package com.ruoyi.lowcode.controller;

import com.ruoyi.lowcode.domain.VoteInfo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@Controller
@RequestMapping("/lowcode/vote")
public class VoteController {
    private String prefix = "lowcode/vote";

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping()
    public String student()
    {
        return prefix + "/vote";
    }

    @GetMapping("/votelist")
    @ResponseBody
    public HashMap<String,Object> votelist() throws Exception {
        String key = "vote";
        redisTemplate.opsForZSet().add(key,"luffy",100);
        redisTemplate.opsForZSet().add(key,"zoro",200);
        redisTemplate.opsForZSet().add(key,"nami",300);

        Set<DefaultTypedTuple> set = redisTemplate.opsForZSet().rangeWithScores(key, 0, -1);
        List<String> nameList = new ArrayList<>();
        List<Double> valueList = new ArrayList<>();
        for (DefaultTypedTuple tuple : set) {
            nameList.add(tuple.getValue().toString());
            Double score = tuple.getScore();
            valueList.add(score);

        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("candidates",nameList);
        hashMap.put("values",valueList);

        return hashMap;
    }


    @PostMapping("/vote")
    public void vote(@RequestBody VoteInfo voteInfo) {
        // 保存投票信息到数据库
        saveVoteToDatabase(voteInfo);

        // 将投票流水信息格式化为JSON
        String voteJson = convertToJson(voteInfo);

        // 发送投票消息到MQ
        sendMessageToMQ(voteJson);
    }

    // 将投票信息保存到数据库
    private void saveVoteToDatabase(VoteInfo voteInfo) {
        // TODO: 实现保存投票信息到数据库的逻辑
    }

    // 将投票信息转换为JSON字符串
    private String convertToJson(VoteInfo voteInfo) {
        // TODO: 实现将投票信息格式化为JSON的逻辑
        return ""; // 返回格式化后的JSON字符串
    }

    // 发送投票信息到MQ
    private void sendMessageToMQ(String voteJson) {
        // 发送消息到MQ Exchange为"vote-exchange"，Routing Key为"vote.new"
        rabbitTemplate.convertAndSend("vote-exchange", "vote.new", voteJson);
    }
}
